import IpcMainHandle, { registerServiceInstance } from '../decorator/ipc_main_handle'
import BaseService from './base_service'

// 用户信息接口
interface UserInfo {
  id: number
  username: string
  name: string
  avatar?: string
  role: string
  loginTime: string
}

// 登录结果接口
interface LoginResult {
  success: boolean
  message?: string
  token?: string
  userInfo?: UserInfo
}

class UserService extends BaseService<UserService> {
  // 模拟用户数据库
  private users = [
    {
      id: 1,
      username: 'admin',
      password: '123456',
      name: '管理员',
      avatar: '',
      role: 'admin'
    },
    {
      id: 2,
      username: 'user',
      password: '123456',
      name: '普通用户',
      avatar: '',
      role: 'user'
    }
  ]

  private constructor() {
    super()
  }

  @IpcMainHandle('userService-login')
  async login(username: string, password: string): Promise<LoginResult> {
    try {
      // 输入验证
      if (!username || !password) {
        return {
          success: false,
          message: '用户名和密码不能为空'
        }
      }

      // 模拟异步验证过程（实际项目中可能是数据库查询）
      await new Promise(resolve => setTimeout(resolve, 300))

      // 查找用户
      const user = this.users.find(u => u.username === username)
      
      if (!user) {
        return {
          success: false,
          message: '用户不存在'
        }
      }

      // 验证密码
      if (user.password !== password) {
        return {
          success: false,
          message: '密码错误'
        }
      }

      // 生成token（实际项目中应该使用JWT等）
      const token = this.generateToken(user.id, user.username)

      // 创建用户信息（不包含密码）
      const userInfo: UserInfo = {
        id: user.id,
        username: user.username,
        name: user.name,
        avatar: user.avatar,
        role: user.role,
        loginTime: new Date().toISOString()
      }

      return {
        success: true,
        message: '登录成功',
        token,
        userInfo
      }
    } catch (error) {
      console.error('登录服务错误:', error)
      return {
        success: false,
        message: '登录服务异常，请稍后重试'
      }
    }
  }

  @IpcMainHandle('userService-logout')
  async logout(): Promise<{ success: boolean; message?: string }> {
    try {
      // 清理session、缓存等
      // 实际项目中可能需要通知服务器等
      return { 
        success: true,
        message: '退出登录成功'
      }
    } catch (error) {
      console.error('退出登录错误:', error)
      return {
        success: false,
        message: '退出登录失败'
      }
    }
  }

  @IpcMainHandle('userService-checkAuth')
  async checkAuth(token: string): Promise<{ success: boolean; message?: string; userInfo?: UserInfo }> {
    try {
      // 验证token有效性
      const decoded = this.verifyToken(token)
      
      if (!decoded) {
        return {
          success: false,
          message: 'Token无效或已过期'
        }
      }

      // 获取用户信息
      const user = this.users.find(u => u.id === decoded.userId)
      
      if (!user) {
        return {
          success: false,
          message: '用户不存在'
        }
      }

      const userInfo: UserInfo = {
        id: user.id,
        username: user.username,
        name: user.name,
        avatar: user.avatar,
        role: user.role,
        loginTime: new Date().toISOString()
      }

      return {
        success: true,
        userInfo
      }
    } catch (error) {
      console.error('身份验证错误:', error)
      return {
        success: false,
        message: '身份验证失败'
      }
    }
  }

  // 生成简单的token（实际项目中应该使用更安全的方式）
  private generateToken(userId: number, username: string): string {
    const timestamp = Date.now()
    const payload = { userId, username, timestamp }
    return Buffer.from(JSON.stringify(payload)).toString('base64')
  }

  // 验证token
  private verifyToken(token: string): { userId: number; username: string; timestamp: number } | null {
    try {
      const payload = JSON.parse(Buffer.from(token, 'base64').toString())
      
      // 检查token是否过期（24小时）
      if (Date.now() - payload.timestamp > 24 * 60 * 60 * 1000) {
        return null
      }
      
      return payload
    } catch {
      return null
    }
  }
}

// 创建并注册服务实例
const userServiceInstance = UserService.getInstance<UserService>()
registerServiceInstance('userService', userServiceInstance)

export default userServiceInstance